import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:delivery_application/common/extension.dart';
import 'package:delivery_application/common/globs.dart';
import 'package:delivery_application/common/service_call.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/home/home_page.dart';
//import 'package:delivery_application/view/login/rest_password_view.dart';
import 'package:delivery_application/view/login/sign_up_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../home/start_deliver.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  TextEditingController txtEmail = TextEditingController();
  TextEditingController txtPassword = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    // 检查用户是否已登录
    _checkLoginStatus();
  }
  
  // 检查登录状态
  Future<void> _checkLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
    
    if (isLoggedIn) {
      // 如果已经登录，直接跳转到首页
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const StartDeliver()),
        );
      }
    }
  }
  
  @override
  Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size; 
    return Scaffold(
      backgroundColor: Color(0xff00AEEE),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(
              vertical: 20,
              horizontal:
                  25),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(
                height: 64,
              ),
              Text(
                "登录",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 50,
                    fontWeight: FontWeight.w800),
              ),

              SizedBox(height: 60), 

              RoundTextfield(
                hintText: "Email",
                controller: txtEmail,
                keyboardType: TextInputType.emailAddress,
              ),

              SizedBox(height: 40), 
              RoundTextfield(
                hintText: "Password",
                controller: txtPassword,
                obscureText: true,
              ),

              SizedBox(height: 40), 
              RoundButton(
                title: "登录",
                onPressed: btnLogin,
              ),

              SizedBox(height: 40), 

              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const SignUpView(),
                    ),
                  );
                },
                child: Text(
                  "没有账号？注册",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 15,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 登录按钮点击事件
  void btnLogin() async {
    if (txtEmail.text.isEmpty || txtPassword.text.isEmpty) {
      _showAlert("请输入邮箱和密码");
      return;
    }
    
    // 获取本地存储的用户信息
    final prefs = await SharedPreferences.getInstance();
    final storedEmail = prefs.getString('userEmail') ?? '';
    final storedPassword = prefs.getString('userPassword') ?? '';
    
    // 验证邮箱和密码
    if (txtEmail.text == storedEmail && txtPassword.text == storedPassword) {
      // 设置登录状态
      await prefs.setBool('isLoggedIn', true);
      
      // 显示登录成功提示
      _showSuccessDialog();
    } else {
      // 登录失败提示
      _showAlert("邮箱或密码错误，请重试");
    }
  }
  
  // 显示提示对话框
  void _showAlert(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text("提示"),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text("确定"),
          )
        ],
      ),
    );
  }
  
  // 显示登录成功对话框
  void _showSuccessDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text("登录成功"),
        content: Text("欢迎回来！"),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 跳转到主页
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => const StartDeliver(),
                ),
              );
            },
            child: Text("进入首页"),
          )
        ],
      ),
    );
  }
}
